package com.bizframework.core.serialization.xml;

import java.beans.*;
import java.io.*;

import com.bizframework.core.serialization.ObjectSerializer;


public class DefaultObjectXMLSerializer implements ObjectSerializer {
	/**
	 * 序列化对象
	 * 
	 * @param obj
	 *            需要序列化的对象
	 * @return String 序列话后的字符串
	 */
	public String serialize(Object obj) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		BufferedOutputStream oos = new BufferedOutputStream(baos);
		XMLEncoder xmlEncoder = new XMLEncoder(oos);
		xmlEncoder.writeObject(obj);
		xmlEncoder.close();
		return baos.toString();
	}

	/**
	 * 反序列化对象
	 * 
	 * @param serializedString
	 *            已序列化的对象字符串
	 * @return 对象
	 */
	@SuppressWarnings("unchecked")
	public <T> T deserialize(Class<T> type, String serializedString) {
		ByteArrayInputStream bais = new ByteArrayInputStream(serializedString.getBytes());
		BufferedInputStream ois = new BufferedInputStream(bais);
		XMLDecoder xmlDecoder = new XMLDecoder(ois);
		Object readObject = xmlDecoder.readObject();
		return (T) readObject;
	}
}